<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/4/25
 * Time: 16:17
 */

namespace App\Wechat\Remind\Logics;

use EasyWeChat\Factory;
use App\Exceptions\ApiException;
use App\Wechat\Remind\Models\User as UserModel;

class Auth
{
	public $app;
	private $config = [
		'app_id' => 'wx75882c29cb6f24fe',
		'secret' => 'ce67ed660df65a4b2b7b089609d796fd',
		'response_type' => 'array',

		'log' => [
			'level' => 'debug',
			'file' => __DIR__.'/wechat.log',
		],
	];

	public function __construct()
	{
		$this->app = Factory::miniProgram($this->config);
	}

	public function userLogin($code, $iv, $encryptedData)
	{
		try{
			$session = $this->app->auth->session($code);
			if (isset($session['errcode']) && $session['errcode'] != 0){
				throw new ApiException('登录Code失效，请稍后再试', 403);
			}
			$decryptedData = $this->app->encryptor->decryptData($session['session_key'], $iv, $encryptedData);
			$user = array_change_key_case($decryptedData, CASE_LOWER);
			unset($user['watermark']);
			$user = UserModel::query()->updateOrCreate(['openid' => $user['openid']], $user);
			$token = auth()->guard('remind')->login($user);
			return $this->responseToken($token);
		}catch (\Exception $exception){
			throw new ApiException('登录失败，请稍后再试', 500);
		}

	}
	
	public function refreshToken()
	{
		$new_token = auth()->guard('remind')->parseToken()->refresh();
		return $this->responseToken($new_token);
	}
	
	private function responseToken($token)
	{
		return [
			'access_token' => $token,
			'token_type' => 'bearer',
			'expires_at' => time() + auth()->guard('remind')->factory()->getTTL() * 60
		];
	}
	
	
}